<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Services\OrderService;
use Dingo\Api\Http\Request;

class PayController extends BaseController
{

    public function wx_notify(Request $request)
    {
        $wx =  $this->payWx();
        $input = $request->input();
        try{
            $data = $wx->verify(); // 是的，验签就这么简单！
            \Log::info('Alipay notify', $data->all());
            $out_trade_no = $data->out_trade_no;
            if (!in_array($data->return_code, ['SUCCESS'])) {
                throw new \Exception("支付状态异常");
            }
//            $out_trade_no = '2020062222985650';
//            $total_amount = '0.02';
//            $trade_no = '11111';
//            OrderService::pay_result($out_trade_no, $total_amount, $trade_no);
            OrderService::pay_result($out_trade_no, $data->total_fee, $data->transaction_id);
            return $wx->success();
        } catch (\Exception $e) {
            \Log::error($e->getMessage());
            return 'error';
        }
    }

    public function wx_query(Request $request) {
        $this->validate($request, [
           'out_trade_no' => 'required'
        ]);
        try{
            $pay_platform = $request->input('pay_platform', 'miniapp');
            if (!in_array($pay_platform, ['miniapp', 'scan'])) {
                return $this->failed('pay_platform类型有误');
            }
            $out_trade_no = \request('out_trade_no');
            $result = $this->payWx()->find(['out_trade_no' => $out_trade_no, 'type' => $pay_platform]);
            if (!in_array($result->trade_state, ['SUCCESS'])) {
                throw new \Exception($result->trade_state);
            }
            OrderService::pay_result($out_trade_no, $result->total_fee, $result->transaction_id);
            return $this->success($result->trade_state);
        } catch (\Exception $e) {
            \Log::error($e->getMessage());
            return $this->failed($e->getMessage());
        }
    }


}